﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SAP.Middleware.Connector;
using CM.DL.DALC.NC03;
using DECOR.BL.BE;

namespace DECOR.DL.DALC.NC03
{
    public class MaterialDALC : IMaterialDALC
    {
        private string _connId = string.Empty;

        public static MaterialDALC Instance(string pConnId)
        {
            if (_instance == null)
            {
                lock (typeof(MaterialDALC))
                {
                    if (_instance == null)
                    {
                        _instance = new MaterialDALC(pConnId);
                    }
                }
            }
            return _instance;
        }
        private MaterialDALC(string pConnId) { this._connId = pConnId; }
        private MaterialDALC() { }
        private static volatile MaterialDALC _instance = null;

        #region IMaterialDALC Members

        public List<DECOR.BL.BE.MaterialBE> buscarMateriales(string pCodAnterior, string pNombre, 
            string pJerarquia, string pOrgVtas, string pCanalDist, string usuarioWeb)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            //InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            string result = "";
            MaterialBE obj = null;
            List<MaterialBE> lsMaterial = new List<MaterialBE>();
            DestConfig dc = new DestConfig();
            try
            {
                //try
                //{
                //    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                //}
                //catch { }
                //RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZWEB_BUSCA_MATERIALES");
                function.SetValue("IM_BISMT", pCodAnterior);
                function.SetValue("IM_MAKTX", pNombre);
                function.SetValue("IM_PRDHA", pJerarquia);
                function.SetValue("IM_VKORG", pOrgVtas);
                function.SetValue("IM_VTWEG", pCanalDist);
                function.SetValue("IM_UNAME", usuarioWeb);
                function.Invoke(dest);

                IRfcTable TMATERIALES = function.GetTable("TABLA_MATERIALES");
                result = function.GetString("EX_RESULT");

                foreach (IRfcStructure item in TMATERIALES)
                {
                    obj = new MaterialBE();

                    obj.CodMaterial = item["MATNR"].GetString();
                    obj.DescMaterial = item["MAKTX"].GetString();
                    obj.CodUMedida = item["MEINS"].GetString();
                    obj.Jerarquia = item["PRDHA"].GetString();
                    obj.Peso = Convert.ToDecimal(item["NTGEW"].GetString());
                    obj.ValorRendimiento = Convert.ToDecimal(item["UMREZ"].GetString());
                    obj.UMedidaRendimiendo = item["MEINH"].GetString();
                    obj.TipoMaterial = item["MFRGR"].GetString();
                    obj.PrecioUnit = Convert.ToDecimal(item["NETPR"].GetString());
                    obj.Tipo = item["MTART"].GetString();
                    obj.TieneServ = item["EXTWG"].GetString().ToUpper() == "SI" ? true : false;
                    obj.Descontinuado = item["DESCONT"].GetString().ToUpper() == "X" ? "D" : "";
                    obj.EspecialServ = item["GROES"].GetString().ToUpper() == "E" ? true : false;
                    obj.EsFlete = item["KTGRM"].GetString().ToUpper().Equals("06") ? true : false;
                    obj.EsEstiba = item["KTGRM"].GetString().ToUpper().Equals("07") ? true : false;
                    obj.Stock = item["STOCK"].GetDecimal();
                    obj.sStock = "";
                    lsMaterial.Add(obj);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lsMaterial;
        }

        public DECOR.BL.BE.MaterialBE leerMaterial(string pCodigo, string pOrgVtas, string pCanalDist, string usuarioWeb)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            //InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            DestConfig dc = new DestConfig();
            MaterialBE obj = null;
            string ex_result = "";

            try
            {
                //try
                //{
                //    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                //}
                //catch { }
                //RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZWEB_LEE_MATERIAL");
                function.SetValue("IM_MATNR", pCodigo);
                function.SetValue("IM_VKORG", pOrgVtas);
                function.SetValue("IM_VTWEG", pCanalDist);
                function.SetValue("IM_UNAME", usuarioWeb);

                function.Invoke(dest);

                IRfcTable MATERIALES = function.GetTable("TABLA_MATERIALES");
                ex_result = function.GetString("EX_RESULT");

                foreach (IRfcStructure item in MATERIALES)
                {
                    obj = new MaterialBE();

                    obj.CodMaterial = item["MATNR"].GetString();
                    obj.DescMaterial = item["MAKTX"].GetString();
                    obj.CodUMedida = item["MEINS"].GetString();
                    obj.Jerarquia = item["PRDHA"].GetString();
                    obj.Peso = Convert.ToDecimal(item["NTGEW"].GetString());

                    obj.ValorRendimiento = Convert.ToDecimal(item["UMREZ"].GetString());
                    obj.UMedidaRendimiendo = item["MEINH"].GetString();
                    obj.TipoMaterial = item["MFRGR"].GetString();
                    obj.PrecioUnit = Convert.ToDecimal(item["NETPR"].GetString());

                    obj.Tipo = item["MTART"].GetString();

                    obj.TieneServ = item["EXTWG"].GetString().ToUpper() == "SI" ? true : false;
                    obj.Descontinuado = item["DESCONT"].GetString().ToUpper() == "X" ? "D" : "";
                    obj.EspecialServ = item["GROES"].GetString().ToUpper() == "E" ? true : false;
                    
                    obj.EsFlete = item["KTGRM"].GetString().ToUpper().Equals("06") ? true : false;
                    obj.EsEstiba = item["KTGRM"].GetString().ToUpper().Equals("07") ? true : false;
                    obj.Stock = Convert.ToDecimal(item["STOCK"].GetString());


                    //mtejada 26.03.2013 - M239-BBP
                    obj.StatusDespacho = "";
                    obj.StockPos = "0.0";
                    break;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return obj;
        }

        public List<DECOR.BL.BE.GenericBE> buscarGrupos(string pCodGrupo)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            //InMemoryDestinationConfiguration dc = new InMemoryDestinationConfiguration();
            DestConfig dc = new DestConfig();
            GenericBE obj = null;
            List<GenericBE> lstGrupos = new List<GenericBE>();
            try
            {
                //try
                //{
                //    RfcDestinationManager.RegisterDestinationConfiguration(dc);
                //}
                //catch { }
                //RfcDestination dest = RfcDestinationManager.GetDestination(this._connId);
                dest = DALC.getDestination(out dc);
                
                function = dest.Repository.CreateFunction("ZWEB_LISTA_GRPMAT");
                function.SetValue("IM_MVGR1", pCodGrupo);
                function.Invoke(dest);

                IRfcTable TVM1T = function.GetTable("T_TVM1T");

                foreach (IRfcStructure item in TVM1T)
                {
                    obj = new GenericBE();

                    obj.Codigo = item["MVGR1"].GetString();
                    obj.Descripcion = item["BEZEI"].GetString();
                    lstGrupos.Add(obj);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lstGrupos;
        }

        #endregion

        //WEBDIST
        public MaterialBE leerMaterial(string pCodigo, string pOrgVtas, string pCanalDist)
        {
            return leerMaterial(pCodigo, pOrgVtas, pCanalDist, "");
        }

        #region IMaterialDALC Members

        /// <summary>
        /// Ejecuta RFC ZCM_SD_003 para devolver lista de materiales
        /// </summary>
        /// <param name="pCod"></param>
        /// <param name="pCodAnt"></param>
        /// <param name="pDesc"></param>
        /// <param name="pJerarquia"></param>
        /// <param name="pOrgVtas"></param>
        /// <param name="pCanalDist"></param>
        /// <param name="usuarioWeb"></param>
        /// <returns></returns>
        public List<MaterialBE> buscarMateriales(string pCod, string pCodAnt, string pDesc, string pJerarquia, string pOrgVtas, string pCanalDist, string usuarioWeb)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            List<MaterialBE> lsMaterial = new List<MaterialBE>(); MaterialBE obj = null;
            DestConfig dc = new DestConfig();
            try
            {
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZCM_SD_003");
                function.SetValue("I_MATNR", pCod);
                function.SetValue("I_BISMT", pCodAnt);
                function.SetValue("I_MAKTX", pDesc);
                function.SetValue("I_PRDHA", pJerarquia);
                function.SetValue("I_VKORG", pOrgVtas);
                function.SetValue("I_VTWEG", pCanalDist);
                function.SetValue("I_UNAME", usuarioWeb);
                function.Invoke(dest);

                IRfcTable TMATERIALES = function.GetTable("T_MATERIALES");
                foreach (IRfcStructure item in TMATERIALES)
                {
                    obj = new MaterialBE();
                    obj.CodMaterial = item["MATNR"].GetString();
                    obj.DescMaterial = item["MAKTX"].GetString();
                    obj.Descripcion = "";
                    obj.CodUMedida = item["MEINS"].GetString();
                    obj.Jerarquia = item["PRDHA"].GetString();
                    obj.Peso = Convert.ToDecimal(item["NTGEW"].GetString());
                    obj.ValorRendimiento = Convert.ToDecimal(item["UMREZ"].GetString());
                    obj.UMedidaRendimiendo = item["MEINH"].GetString();
                    obj.TipoMaterial = item["MFRGR"].GetString();
                    obj.PrecioUnit = Convert.ToDecimal(item["NETPR"].GetString());
                    obj.Tipo = item["MTART"].GetString();
                    obj.TieneServ = item["EXTWG"].GetString().ToUpper() == "SI" ? true : false;
                    obj.Descontinuado = item["DESCONT"].GetString().ToUpper() == "X" ? "D" : "";
                    obj.EspecialServ = item["GROES"].GetString().ToUpper() == "E" ? true : false;
                    obj.EsFlete = item["KTGRM"].GetString().ToUpper().Equals("06") ? true : false;
                    obj.EsEstiba = item["KTGRM"].GetString().ToUpper().Equals("07") ? true : false;
                    obj.Stock = Convert.ToDecimal(item["STOCK"].GetString());
                    obj.Catalogo = item["CATALOGO"].GetString();
                    obj.sStock = "";
                    lsMaterial.Add(obj);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }
            return lsMaterial;
        }

        #endregion

        /// <summary>
        /// Número de Material
        /// </summary>
        /// <param name="pNumMat"></param>
        /// <returns></returns>
        public List<EnlaceMaterialBE> buscarMaterialesAdicionales(string pNumMat, string pWerks)
        {
            IRfcFunction function = null; RfcDestination dest = null;
            List<EnlaceMaterialBE> lsMaterial = new List<EnlaceMaterialBE>(); 
            EnlaceMaterialBE obj = null;
            List<EstructuraPosicinListaMateriales> lstMaterialPos = new List<EstructuraPosicinListaMateriales>();
            EstructuraPosicinListaMateriales objMaterialPos = new EstructuraPosicinListaMateriales();
            DestConfig dc = new DestConfig();
            try
            {
                dest = DALC.getDestination(out dc);
                function = dest.Repository.CreateFunction("ZCM_SD_012");
                function.SetValue("IM_MATNR", pNumMat);
                function.SetValue("IM_WERKS", pWerks);

                function.Invoke(dest);

                IRfcTable TMATERIALESHeader = function.GetTable("T_MAT_HEADER");
                IRfcTable TMATERIALESDetail = function.GetTable("T_MAT_DETAILS");
                foreach (IRfcStructure item in TMATERIALESHeader)
                {
                    if (item["WERKS"].GetString().Trim() != "")
                    {
                        obj = new EnlaceMaterialBE();
                        obj.Matnr = item["MATNR"].GetString();
                        obj.Werks = item["WERKS"].GetString();
                        obj.Stlan = item["STLAN"].GetString();
                        obj.Stlnr = item["STLNR"].GetString();
                        obj.Stlal = item["STLAL"].GetString();
                        obj.Losvn = Convert.ToDecimal(item["LOSVN"].GetString());
                        obj.Losbs = Convert.ToDecimal(item["LOSBS"].GetString());
                        obj.Maktx = item["MAKTX"].GetString();
                        foreach (IRfcStructure itemX in TMATERIALESDetail)
                        {
                            if (item["STLAL"].GetString() == itemX["STLAL"].GetString() && item["WERKS"].GetString() == itemX["WERKS"].GetString())
                            {
                                objMaterialPos = new EstructuraPosicinListaMateriales();
                                objMaterialPos.Matnr = itemX["MATNR"].GetString();
                                objMaterialPos.WERKS = itemX["WERKS"].GetString();
                                objMaterialPos.STLAL = itemX["STLAL"].GetString();

                                obj.PosicionListaMateriales.Add(objMaterialPos);
                            }
                        }
                        lsMaterial.Add(obj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                //RfcDestinationManager.UnregisterDestinationConfiguration(dc);
            }

            return lsMaterial;

        }
    }
}
